package com.example.fruitdb.service;

import com.example.fruitdb.entity.Fruit;
import com.example.fruitdb.mapper.FruitMapper;
import com.example.fruitdb.util.GetSQLSession;
import org.apache.ibatis.session.SqlSession;

import java.util.Vector;


public class FruitService {
    public Vector<Fruit> getAll() {
        Vector<Fruit> v;
        SqlSession session = GetSQLSession.createSQLSession();
        FruitMapper fruitMapper = session.getMapper(FruitMapper.class);
        v = fruitMapper.queryAllFruit();
        session.close();
        return v;
    }

    public Vector<Fruit> getFruitByName(String fruitName) {
        Vector<Fruit> v;
        SqlSession session = GetSQLSession.createSQLSession();
        FruitMapper fruitMapper = session.getMapper(FruitMapper.class);
        v = fruitMapper.queryFruitByName(fruitName);
        session.close();
        return v;
    }


    public boolean deleteFruit(Integer fruitID)
    {
        try
        {
            SqlSession session = GetSQLSession.createSQLSession();
            FruitMapper fruitMapper = session.getMapper(FruitMapper.class);
            fruitMapper.deleteFruit(fruitID);
            session.commit();
            session.close();
            return true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    public boolean modifyFruit(Fruit fruit)
    {
        try {
            SqlSession session = GetSQLSession.createSQLSession();
            FruitMapper fruitMapper = session.getMapper(FruitMapper.class);
            fruitMapper.modifyFruit(fruit);
            session.commit();
            session.close();
            return true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    public boolean insertFruit(Fruit fruit)
    {
        try {
            SqlSession session = GetSQLSession.createSQLSession();
            FruitMapper fruitMapper = session.getMapper(FruitMapper.class);
            fruitMapper.insertFruit(fruit);
            session.commit();
            session.close();
            return true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

}
